package com.zentrale1.noodlemail.classifiers;

import com.zentrale1.noodlemail.Mail;
import com.zentrale1.noodlemail.Noodlemail;

import weka.classifiers.Classifier;
import weka.classifiers.bayes.NaiveBayes;
import weka.core.*;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.StringToWordVector;

/*
 * The MIT License
 * 
 * Copyright (c) 2010 Andreas Fleig
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */


/**
 * Wrapper to Weka's NaiveBayes classifier
 * More or less a copy of the example implementation in 
 * Ian Witten and Eibe Frank, "Data Mining - Practical Machine Learning Tools 
 * and Techniques", Second Edition, pages 463ff. 
 * @author afleig
 *
 */
public class WekaWrapper extends NoodleClassifier
{

	private Instances data;
	private StringToWordVector filter;
	private Classifier classifier;
	final static String SUBJECT = "subject";
	final static String BODY = "body";
	// space in class attribute name -- to avoid attribute collisions with 
	// word attributes 
	final static String CLASS = "class attr";
	final static String DATA_NAME = "noodlemail";
	final static int INITIAL_CAPACITY = 1000;
	private boolean uptodate;
	
	
	public WekaWrapper(String[] folderNames)
	{
		super(folderNames);
		
		filter = new StringToWordVector();
		classifier = new NaiveBayes();
		
		// attribute vector
		FastVector attributes = new FastVector(3);
		attributes.addElement(new Attribute(SUBJECT, (FastVector)null));
		attributes.addElement(new Attribute(BODY, (FastVector)null));
		// folder names
		FastVector folders = new FastVector(folderNames.length);
		for (String f : folderNames) {
			folders.addElement(f);
		}
		Attribute classAttribute = new Attribute(CLASS, folders);
		attributes.addElement(classAttribute);
		
		data = new Instances(DATA_NAME, attributes, INITIAL_CAPACITY);
		data.setClass(classAttribute);
		uptodate = false;
	}
	
	
	@Override
	protected Result[] _classify(Mail mail) 
	{
		Result[] results = null;
		try {
			if (!uptodate) {
				// build classifier model
				Noodlemail.log("  Building classifier model...");
				filter.setInputFormat(data);
				Instances filteredData = Filter.useFilter(data, filter);
				classifier.buildClassifier(filteredData);
				uptodate = true;
			}
			
			Instances test = data.stringFreeStructure();
			Instance testInstance = makeInstance(mail, test);
			filter.input(testInstance);
			Instance filteredInstance = filter.output();
			
			
			double[] dist = classifier.distributionForInstance(filteredInstance);
			//System.out.println("len: "+dist.length);
			results = new Result[dist.length];
			for (int i=0; i<dist.length; i++) {
				results[i] = new Result(folderNames[i], dist[i]);
				//System.out.println(folderNames[i] + ": "+dist[i]);
			}
		
		} catch (Exception e) {
			e.printStackTrace();
		}

		return results;
	}

	
	@Override
	protected void _train(Mail mail, String category) 
	{
		Instance instance = makeInstance(mail, data);
		instance.setClassValue(category);
		data.add(instance);
		uptodate = false;
	}
	
	private Instance makeInstance(Mail mail, Instances data)
	{
		Instance instance = new Instance(3);
		
		Attribute subject = data.attribute(SUBJECT);
		instance.setValue(subject, mail.getSubject());
		
		Attribute body = data.attribute(BODY);
		instance.setValue(body, mail.getTextBody());
		
		instance.setDataset(data);
		return instance;
	}

	
	@Override
	public String getName() 
	{
		return "Weka NaiveBayes";
	}

}
